<?php
// 响应函数
function success($data = [], $msg = '操作成功') {
    echo json_encode(['status' => 'success', 'data' => $data, 'msg' => $msg]);
    exit;
}
function error($msg) {
    echo json_encode(['status' => 'error', 'msg' => $msg]);
    exit;
}

// 验证登录
session_start();
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    error('请先登录管理员账号');
}

// 数据库连接
$host = 'localhost';
$dbname = 'itops_help1_center';
$username = 'itops_help1_center';
$password = 'itops_help1_center';
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    error('数据库连接失败：' . $e->getMessage());
}

// 处理操作
$action = $_REQUEST['action'] ?? '';
switch ($action) {
    // 新增文章
    case 'add':
        $title = trim($_POST['title'] ?? '');
        $category = trim($_POST['category'] ?? '未分类'); // 分类字段
        $content = trim($_POST['content'] ?? '');
        $status = intval($_POST['status'] ?? 0);
        $createTime = $_POST['create_time'] ?? date('Y-m-d H:i:s');

        if (empty($title) || empty($content)) {
            error('标题和内容不能为空');
        }

        $stmt = $pdo->prepare("INSERT INTO article (title, category, content, status, create_time) 
            VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$title, $category, $content, $status, $createTime]);
        success([], '文章新增成功');
        break;

    // 编辑文章
    case 'edit':
        $id = intval($_POST['id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $category = trim($_POST['category'] ?? '未分类'); // 分类字段
        $content = trim($_POST['content'] ?? '');
        $status = intval($_POST['status'] ?? 0);

        if ($id <= 0 || empty($title) || empty($content)) {
            error('参数错误');
        }

        $stmt = $pdo->prepare("UPDATE article SET title=?, category=?, content=?, status=? WHERE id=?");
        $stmt->execute([$title, $category, $content, $status, $id]);
        success([], '文章修改成功');
        break;

    // 删除文章（之前的代码保持不变）
    case 'delete':
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) {
            error('无效的文章ID');
        }
        $stmt = $pdo->prepare("DELETE FROM article WHERE id = ?");
        $stmt->execute([$id]);
        if ($stmt->rowCount() > 0) {
            success([], '删除成功');
        } else {
            error('文章不存在');
        }
        break;

    default:
        error('无效操作');
}